import { Module } from "vuex";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { User, LoginForm } from "@/entity/User";
import { login, getUserInfo } from "@/api/user";

export interface UserState {
  token: string;
  userInfo: User;
}

export interface UserGetters {
  // 是否登录
  "user/isLogin": boolean;
}

export interface UserMutations {
  // 设置token
  "cart/SetToken": string;
  // 删除token
  "cart/RemoveToken": any;
}

export interface UserActions {
  // 登录
  "user/login": {
    payload: LoginForm;
    // promise: string;
    promise: User;
  };
  // 获取用户信息
  "user/getUserInfo": {
    payload: any;
    promise: User;
  };
}

const user: Module<UserState> = {
  namespaced: true,
  state: {
    token: getToken() || "",
    userInfo: {},
  },
  getters: {
    // 是否登录
    isLogin: (state) => state.token && state.userInfo.userId,
  },
  mutations: {
    // 设置 token
    SetToken(state, token: string) {
      setToken(token);
      state.token = token;
    },
    // 删除 token
    RemoveToken(state) {
      removeToken();
      state.token = "";
    },
    // 设置用户信息
    SetUserInfo(state, userInfo: User) {
      state.userInfo = userInfo;
    },
  },
  actions: {
    // 登录
    login({ commit, dispatch }, form: LoginForm) {
      return login(form).then((token) => {
        commit("SetToken", token);

        return dispatch("getUserInfo");
      });
    },
    // 获取用户信息
    getUserInfo({ commit }) {
      return getUserInfo().then((userInfo) => {
        commit("SetUserInfo", userInfo);

        return userInfo;
      });
    },
  },
};

export default user;
